﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using Gpsys.Web.Models;
using Gpsys.Web.Common;
using Gpsys.Web.Business;

namespace Gpsys.Web.Controllers
{
    public class AccountController : Controller
    {

        //
        // GET: /Account/LogOn

        public ActionResult LogOn()
        {
            LogOnModel model = new LogOnModel();
            return View(model);
        }

        //
        // POST: /Account/LogOn

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            ViewBag.Valid = false;
            if (ModelState.IsValid)
            {
                UserBusiness bs = new UserBusiness();
                var user = bs.GetUser(model.UserName);

                if (user != null && user.IsDeleted == false && model.Password == "123456")
                {
                    ViewBag.Valid = true;

                    UserHelpers.UserName = user.UserName;
                    UserHelpers.Name = user.Name;

                    user.LastLogin = DateTime.Now;
                    bs.UpdateUser(user);

                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/LogOff
        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();

            return RedirectToAction("Index", "Home");
        }
    }
}
